#!/usr/bin/env ruby
# - repo_name
# - project_name
# - pull_number

require 'json'
require 'rest-client'
require "#{ENV['LKP_SRC']}/lib/log.rb"
require "#{ENV['LKP_SRC']}/lib/write_json.rb"

BASE_URL = "https://majun.osinfra.cn/api/http/majun-service-forwarding/ci-portal/poison/webhook"

class MajunScanVirus
  def initialize
    @resource = RestClient::Resource.new(BASE_URL)
    @api_token = ENV["secrets_api_token"]
    @repo_name = ENV["repo_name"]
    @project_name = ENV["project_name"]
    @pull_number = ENV["pull_number"]
    @access_token = ENV["secrets_access_token"]
  end

  def wait_scan_virus_finish(data)
    while true
      begin
        response = @resource["query-pr-results-status"].post(data.to_json, :content_type => 'application/json')
      rescue Exception => e
        log_warn "Failed to query scan virus result from Majun: #{e.message}"
        raise e
      end
      
      body = JSON.parse(response.body)
      log_info response.body
      code = body["code"]
      result = body.fetch("result", {})
      
      if code ==  200 && !result.empty?
        is_pass = result["isPass"]
        url = result["url"]
        result["state"] = is_pass ? 'Passed' : 'Unpassed'

        log_info "Succeed in getting scan virus result from Majun: #{body}"
        write_json result, "majun-scan-virus-result"

        break if is_pass
        
        raise "Not passed!"
      else
        log_warn "Unknown code of response: #{code}"
      end

      log_info "Waiting 30 seconds for next query..."
      sleep 30
    end
  end

  def run
    data = {
      :repoName => @repo_name,
      :projectName => @project_name,
      :pullNumber => @pull_number,
      :apiToken => @api_token,
      :access_token => @access_token
    }

    begin
      response = @resource['pr-scan'].post(data.to_json, :content_type => 'application/json')
    rescue Exception => e
      log_error "Failed to create scan virus task from Majun: #{data.to_json} => #{response}"
      raise e
    end
      
    raise "Failed to create scan virus task from Majun: #{response}" unless response.code == 200

    body = JSON.parse(response.body)
    log_info body
    begin
      scan_id = body["result"]["scanId"]
    rescue
      raise "Failed to create scan virus task from Majun: #{response}"
    end

    query_data = {
      :scanId => scan_id,
      :apiToken => @api_token
    }

    wait_scan_virus_finish query_data
  end
end

MajunScanVirus.new.run
